package com.example.bigevent.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.example.bigevent.pojo.User;
import com.example.bigevent.mapper.UserMapper;
import com.example.bigevent.service.IUserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.bigevent.utils.Md5Util;
import com.example.bigevent.utils.ThreadLocalUtil;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.Map;

/**
 * <p>
 * 用户表 服务实现类
 * </p>
 *
 * @author author
 * @since 2024-05-30
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {

    /**
     * 根据用户名查询用户
     * @param username
     * @return
     */
    @Override
    public User getByUsername(String username) {
        return getOne(new LambdaQueryWrapper<User>().eq(User::getUsername, username));
    }

    /**
     * 更新用户基本信息
     * @param user
     */
    @Override
    public void updateUserInfo(User user) {
        update(new LambdaUpdateWrapper<User>().eq(User::getUsername, user.getUsername())
                .set(User::getUsername,user.getUsername())
                .set(User::getNickname,user.getNickname())
                .set(User::getEmail,user.getEmail())
                .set(User::getUpdateTime, LocalDateTime.now()));
    }
    /**
     * 更新用户头像
     * @param avatarUrl
     */
    @Override
    public void updateAvatar(String avatarUrl) {
        Map<String,Object> map = ThreadLocalUtil.get();
        Integer id = (Integer) map.get("id");
        User user = User.builder()
                .id(id)
                .updateTime(LocalDateTime.now())
                .userPic(avatarUrl)
                .build();
        updateById(user);
    }
    /**
     * 更新用户密码
     * @param newPwd
     */
    @Override
    public void updatePwd(String newPwd) {
        Map<String,Object> map = ThreadLocalUtil.get();
        Integer id = (Integer) map.get("id");
        User user = User.builder()
                .id(id)
                .password(Md5Util.getMD5String(newPwd))
                .updateTime(LocalDateTime.now())
                .build();
        updateById(user);
    }
}
